//
//  KBaseViewController.swift
//  YZFetter
//
//  Created by 康凯 on 2017/7/17.
//  Copyright © 2017年 康凯. All rights reserved.
//

import UIKit

open class KBaseViewController: UIViewController, UIGestureRecognizerDelegate {

    public var isNavigationBarHiddenInController: Bool {
        return navigationBarHidden
    }
    
    fileprivate var navigationBarHidden = false
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        
        if self.navigationController?.topViewController == self {
            let leftBarButton = UIBarButtonItem.init(image: bundleImage(name: "icon_nav_back"), style: .plain, target: self, action: #selector(backAction(item:)))
            self.navigationItem.leftBarButtonItem = leftBarButton
        }
    }
    
    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationBarHidden = self.navigationController?.isNavigationBarHidden ?? false
    }
    
    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if ((self.navigationController != nil) && (self.navigationController?.viewControllers.contains(self))! && (self.navigationController?.topViewController?.isKind(of: KBaseViewController.self))!){
            let controller: KBaseViewController = self.navigationController?.topViewController as! KBaseViewController
            self.navigationController?.setNavigationBarHidden(controller.isNavigationBarHiddenInController, animated: true)
        }
    }
    
    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    override open var shouldAutorotate: Bool {
        return false
    }
    
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    open func backAction(item: UIBarButtonItem) {
        if self.presentingViewController != nil {
            self.dismiss(animated: true, completion: nil)
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    private func bundleImage(name: String) -> UIImage? {
        let bundlePath = Bundle.init(for: KBaseViewController.self).path(forResource: "\(name)@\(Int(UIScreen.main.scale))x", ofType: "png", inDirectory: "common.bundle/images")
        guard let path = bundlePath else {
            return nil
        }
        return UIImage.init(contentsOfFile: path)
    }
    
}
